package lc20240508;

public class Demo2 {
    public static void main(String[] args) {
        String s = "[";
        System.out.println(isValid(s));
    }

    public static boolean isValid(String s) {
        int n = s.length();
        MyStack stack = new MyStack(n);

        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            //如果是左边的括号，push进栈。
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                //肯定得有右边的括号与之匹配，不然就是false。
                if (stack.isEmpty())
                    return false;
                char topCh = stack.pop();
                //应该吧c的判断条件放到前面，如果c不符合直接判负。
                if (c != ')' && topCh == '('
                        || c != ']' && topCh == '['
                        || c != '}' && topCh == '{') {
                    return false;
                }
            }
        }
        //如果正确，则栈是空的，因为都pop出去了。其实我觉得也可以返回true.
        //不能直接写返回true,因为如果只有一个括号，也是得返回false，所以要加isEmpty,否则最后得加判空条件。
        return stack.isEmpty();
//        return true;
    }
}

class MyStack {
    private char[] stack;
    private int top;

    public MyStack(int capacity) {
        stack = new char[capacity];
        top = -1;
    }

    public void push(char item) {
        if (top == stack.length - 1) {
            // Stack is full, need to resize or throw an exception
            System.out.println("Stack is full, cannot push element.");
        } else {
            top++;
            stack[top] = item;
        }
    }

    public char pop() {
        if (top == -1) {
            // Stack is empty, cannot pop
            System.out.println("Stack is empty, cannot pop element.");
            return (char) -1; // Or throw an exception
        } else {
            char popped = stack[top];
            top--;
            return popped;
        }
    }

    public char peek() {
        if (top == -1) {
            System.out.println("Stack is empty, cannot peek element.");
            return (char) -1; // Or throw an exception
        } else {
            return stack[top];
        }
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public int size() {
        return top + 1;
    }
}
